<template>
	<view class="login-container">
		<!-- 提示登录的图标 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<button type="primary" @click="getUserProfile" class="btn-login">一键登录</button>
		<text class="tips">登录之后尽享更多权益</text>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'

	export default {
		name: "my-login",
		data() {
			return {

			};
		},
		methods: {
			...mapMutations('user', ['updateUserInfo', 'updateUserId']),
			// 获取用户信息
			getUserProfile() {
				uni.getUserProfile({
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						this.updateUserInfo(res.userInfo);
						this.getUserId();
					},
					fail: (err) => {
						return uni.$showMsg("您取消了授权！")
					}
				});
			},
			// 获取用户id
			async getUserId() {
				// 获取code
				const [err, res] = await uni.login().catch(err => err)
				// 请求失败
				if(err || res.errMsg !== "login:ok") return uni.$showMsg('登录失败')
				
				// 获取用户id
				const {data :loginResult } = await uni.$http.post('/api/user/new', {
					code: res.code
				}).catch(err => err)
				if(loginResult.errno !== 0) return uni.$showMsg('登录失败')
				
				// 更新用户id
				this.updateUserId(loginResult.data)
				
			}

		}
	}
</script>

<style lang="scss">
	.login-container {
		height: 750rpx;
		background-color: #f8f8ff;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.btn-login {
			width: 90%;
			border-radius: 100px;
			font-size: 30rpx;
			margin: 15px 0;
		}

		.tips {
			font-size: 12px;
			color: gray;
		}
	}
</style>
